import axios from '@/plugins/Axios';
import { MessageUtils, ProgressUtils } from "@/utils/InteractiveUtils";

interface httpOption {
  params?: objType;
  parent?: string;
  progress?: boolean;
}

export class HttpUtils {
  private static _controller = new AbortController()
  static async get<T>(url: string, option?: httpOption): Promise<T> {
    return await this.ajaxQuest('GET', url, option??{})
  }
  static async post<T>(url: string, option?: httpOption): Promise<T> {
    return await this.ajaxQuest('POST', url, option??{})
  }
  static async patch<T>(url: string, option?: httpOption): Promise<T> {
    return await this.ajaxQuest('PATCH', url, option??{})
  }
  static async delete<T>(url: string, option?: httpOption): Promise<T> {
    return await this.ajaxQuest('DELETE', url, option??{})
  }
  static async upload<T>(url: string, option?: httpOption): Promise<T> {
    return await this.ajaxQuest('UPLOAD', url, option??{})
  }
  static async ajaxQuest<T>(
    type: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'UPLOAD',
    url: string,
    option: httpOption
  ): Promise<T> {
    ProgressUtils.start(option?.parent);
    try {
      switch (type) {
        case 'GET':
          return (await axios.get<T>(url, {
            signal: this._controller.signal,
            params: { ...option.params }
          })) as T
        case 'POST':
          return (await axios.post<T>(url, option.params, {
            signal: this._controller.signal
          })) as T
        case 'PATCH':
          return (await axios.patch<T>(url, {
            signal: this._controller.signal
          })) as T
        case 'DELETE':
          return (await axios.delete<T>(url, {
            signal: this._controller.signal,
            params: { ...option.params }
          })) as T
        case 'UPLOAD':
          return (await axios.postForm<T>(url, option.params, {
            signal: this._controller.signal
          })) as T
        default:
          throw new Error('错误的请求方式')
      }
    } catch (err: any) {
      ProgressUtils.error();
      MessageUtils.error(err);
      throw new Error(err);
    } finally {
      ProgressUtils.close();
    }
  }
  static abort = () => {
    this._controller.abort()
  }
  // 模拟请求
    static async mock<T>(action: Function, time: number = 1000): Promise<T> {
        ProgressUtils.start();
        await new Promise((resolve) => {setTimeout(resolve, time)});
        try {
          const data = action();
          ProgressUtils.success();
          return data as T;
        } catch (err: any) {
          ProgressUtils.error();
          MessageUtils.error(err);
          throw new Error(err);
        } finally {
          ProgressUtils.close();
        }
    }
}
